interface NetworkConfigType {
  method: string;
  url: string;
}

interface responseType<T> {
  status: number;
  timeStamp: number;
  errorCode: number;
  errorMessage: string;
  results: T;
}

export default class Requests {
  constructor() {}

  static loadData<T>(
    networkConfig: NetworkConfigType,
    parameters: {[key: string]: any},
  ): Promise<T> {
    var url = '';
    var serializationBody = '';
    if (networkConfig.method === 'GET') {
      url = serializationParametersToUrl(networkConfig.url, parameters);
    } else {
      url = networkConfig.url;
      serializationBody = JSON.stringify(parameters);
    }
    return new Promise((resolve, reject) => {
      fetch(url, {
        method: networkConfig.method,
        body: serializationBody,
      })
        .then(response => {
          if (response.status === 200) {
            return response.json();
          } else {
            reject('code = ' + response.status);
          }
        })
        .then((responseJson: responseType<T>) => {
          // console.log('Response JSON : ', responseJson)
          resolve(responseJson.results);
        })
        .catch(error => {
          console.log('Response Error : ', JSON.stringify(error));
          reject(JSON.stringify(error));
        });
    });
  }
}

function serializationParametersToUrl(
  url: string,
  parameters: {[key: string]: any},
): string {
  if (parameters && Object.keys(parameters).length > 0) {
    var paramsArray: string[] = [];
    Object.keys(parameters).forEach(key =>
      paramsArray.push(key + '=' + parameters[key]),
    );
    if (url.search(/\?/) === -1) {
      url += '?' + paramsArray.join('&');
    } else {
      url += '&' + paramsArray.join('&');
    }
  }
  return url;
}